package com.example.demo.interceptors;


import com.example.demo.beans.JwtSignatureStatus;
import com.example.demo.config.AppProperties;
import com.example.demo.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private AppProperties appProperties;
    private JwtUtils jwtUtils;

    public JwtInterceptor(AppProperties appProperties, JwtUtils jwtUtils) {
        this.appProperties = appProperties;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS 也是一种请求，
        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        // 获取到请求头中的 authentication
        String authorization = request.getHeader(appProperties.getJwt().getHeader());
        if(StringUtils.hasText(authorization)) {
            // 截取活的 jwt 字符串
            String access_token = authorization.substring(appProperties.getJwt().getJwtPrefix().length());
            JwtSignatureStatus jwtSignatureStatus = jwtUtils.validateAccessToken(access_token);
            switch (jwtSignatureStatus.getStatus()) {
                case correct:
                    return true;
                case expire:
                    response.setStatus(401);  // 返回 401， 表示用户需要重新登录
                    return false;
                case tamper:
                    // TODO 在实际企业级应用，此时当前用户的ip被纳入 风控
                    response.setStatus(401);
                    return false;
            }
            return true;
        }else {
            response.setStatus(401);  // 返回 401， 表示用户需要重新登录
            return false;
        }
    }
}
